# -*- coding:utf-8 -*-

from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi.responses import JSONResponse

from core.response import success

from app.repository.user import UserRepository
from app.repository import get_user_repo
from app.service.auth import get_token_data, password_hash, virify_password
from app.service.auth import create_access_token, create_refresh_token

router = APIRouter(prefix="/auth")


@router.get("/password", response_model=str)
async def password_test(password:str):
    return password_hash(password)

@router.post("/oauth2", summary="登录")
async def login(form_data: OAuth2PasswordRequestForm = Depends(), repo: UserRepository = Depends(get_user_repo)):
    db_user = await repo.get_user_by_username(form_data.username)
    if db_user is None:
        # raise HTTPException(status_code=400, detail="Incorrect username or password")
        return JSONResponse(status_code=400, content={"message": "Incorrect username or password"})
    if not virify_password(form_data.password, db_user.password):
        # raise HTTPException(status_code=400, detail="Incorrect username or password")
        return JSONResponse(status_code=400, content={"message": "Incorrect username or password"})
    access_token = create_access_token({"sub": form_data.username})
    refresh_token = create_refresh_token({"sub": form_data.username})
    # return success(data={"access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer"})
    return {"access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer"}


@router.get("/refresh", summary="token 刷新")
async def refresh_token(token_data: dict=Depends(get_token_data), repo: UserRepository = Depends(get_user_repo)):
    db_user = await repo.get_user_by_username(token_data["sub"])
    if db_user is None:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token = create_access_token({"sub": form_data.username})
    refresh_token = create_refresh_token({"sub": form_data.username})
    # return success(data={"access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer"})
    return {"access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer"}


